﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Citi.RoutineBase;
using Citi.Helpers;
using System.IO;
using System.Threading;
using System.Globalization;
using Citi.Import.Util;
using Citi.ResourceConsolidation.Domain;

namespace Citi.ResourceConsolidation.SchedulerUI.NEMS
{
    public class NEMSUpdateDatabase : IExecutableRoutine
    {

        private readonly string inputNEMSFolder = @"\\gruvnascti0016.wlb.lac.nsroot.net\DATA_GRP1\FTOOLS\Apps\RHNEMS\ExtractedFiles\NEMS";

        public IEnumerable<RoutineParameter> Parameters
        {
            get { return null; }
        }

        public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            
        }

        public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            var roboUsername = parameters["RobotUsername"].ToString();
            var roboPassword = parameters["RobotPassword"].ToString();

            using (NetworkShareAccesser.Access(inputNEMSFolder, roboUsername, roboPassword))
            {
                currentAction.Description = string.Format("Looking for NEMS file in {0}: ", inputNEMSFolder);

                var fileName = Directory.GetFiles(inputNEMSFolder).OrderByDescending(x => File.GetLastWriteTime(x)).First();

                currentAction.Description = string.Format("The file {0} was found", Path.GetFileName(fileName));
                UpdateNEMS(fileName, ref currentAction);
            }
        }

        public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            
        }

        private static void UpdateNEMS(string fileName, ref ICurrentAction currentAction)
        {
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US");

            List<Error> errors = null;
            currentAction.Description = "Reading NEMS File";

            var dataTable = Conversion.ReadExcel(fileName, ref errors, null, 1);
            var referenceDate = DateTime.ParseExact(Path.GetFileName(fileName.ToString()).Substring(5, 8), "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);

            List<Resource> resources;

            errors = ResourceUpdateDatabase.ImportResourceConsolidation(referenceDate, currentAction, errors, dataTable, ResourceType.NEMS, out resources);

        }

        IEnumerable<RoutineParameter> IExecutableRoutine.Parameters
        {
            get { throw new NotImplementedException(); }
        }
    }
}
